import { useEffect, useState } from "react"
import { Modal, Form, Input, Button, message } from "antd"
import { itemType } from "./type"
import style from './index.module.scss'
import { AddUserFnc, GetUserInfoFnc, EditUserFnc } from '@/api/user'
import ProTypes from 'prop-types'

const AddEditDialog = ({isModalOpen, changeDialog, dialogType, init, ipt, pageNow, pageSize, userID}: itemType) => {

  // 获取form实例, 用来清空form
  const [form] = Form.useForm();

  // 用于做比较的form
  const [formObj, setFormObj] = useState({})

  // 打开修改盒子 数据初始化
  const initFnc = async () => {
    if(dialogType === 'edit') {
      const res = await GetUserInfoFnc(userID)
      if(res.data.meta.status === 200) {
        form.setFieldsValue({
          id: res.data.data.id,
          username: res.data.data.username,
          email: res.data.data.email,
          mobile: res.data.data.mobile
        })
        setFormObj({
          username: res.data.data.username,
          email: res.data.data.email,
          mobile: res.data.data.mobile
        })
      }
    }
  }

  useEffect(() => {
    initFnc()
  }, [userID])

  // 邮箱和电话 验证逻辑
  const checkEmailorMobile = (reg: any, value: string, text: string) => {
   if(value === undefined || reg.test(value) === false) {
    return Promise.reject(text)
   } else {
    return Promise.resolve()
   }
  }

  // valida 邮箱和电话
  const validateEmail = (rules: any, value: string ) => {
    if(rules.field === 'email') {
     const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
     return checkEmailorMobile(regEmail, value, '请输入合法邮箱')
    } else {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      return checkEmailorMobile(regMobile, value, '请输入合法的手机号')
    }
  }

  // 公共消息
  const publicMsg = (msg: string) => {
    message.success(msg, 1.5, () => {
      changeDialog(false)
      init(ipt, pageNow, pageSize)
      form.setFieldsValue({username: "", password: "", email: "", mobile: ""})
    })
  }

  // 添加用户 修改用户
  const onFinish = async (info: {username: string, password: string, email: string, mobile: string}) => {
    if(dialogType === 'add') {
      const res = await AddUserFnc(info)
      if(res.data.meta.status === 201) { // 添加
        publicMsg(res.data.meta.msg)
      }
    } else {
      if(JSON.stringify(formObj) === JSON.stringify(info)) {
        changeDialog(false)
      } else {
        const res =  await EditUserFnc(userID, info)
        publicMsg(res.data.meta.msg)
      }
    }
  }

  return (
    <Modal title={dialogType === 'add' ? '添加用户' : '修改用户'} open={isModalOpen} footer={null} onCancel={() => changeDialog(false)}>
       <Form form={form} className={style.form} onFinish={onFinish} labelCol={{ span: 4 }}>
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }, {min: 3, max: 10, message: '长度在3-10个字符'}]}>
            <Input disabled={dialogType === 'edit' ? true : false}/>
          </Form.Item>
            
          {
            dialogType === 'add' 
            ? <Form.Item name="password" label="密码" rules={[{required: true, message: '请输入密码'}, {min: 3, max: 10, message: '长度在3-10个字符'}]}>
              <Input.Password autoComplete=""/>
            </Form.Item> 
            :  ''
          }

          <Form.Item name="email" label="邮箱" rules={[{required: true, validator: (rule,value) => validateEmail(rule, value)}]}>
            <Input />
          </Form.Item>

          <Form.Item name="mobile" label="手机号" rules={[{required: true, validator: (rule,value) => validateEmail(rule, value)}]}>
            <Input/>
          </Form.Item>

          <Form.Item style={{marginBottom: 0}}>
            <div className={style.btn}>
              <Button type="primary" htmlType="submit">{dialogType === 'add' ? '添加' : '修改'}</Button>
              <Button type="default" onClick={() =>changeDialog(false)}>取消</Button>
            </div>
          </Form.Item>
        </Form>
    </Modal>
  )
}

export default AddEditDialog
AddEditDialog.proTypes = {
  isModalOpen: ProTypes.bool.isRequired,
  changeDialog: ProTypes.func.isRequired,
  dialogType: ProTypes.string.isRequired,
  init: ProTypes.func.isRequired,
  ipt: ProTypes.string.isRequired,
  pageNow: ProTypes.number.isRequired,
  pageSize: ProTypes.number.isRequired,
  userID: ProTypes.number.isRequired
}